class Solution
{
public:
    vector<vector<int>> resultGrid(vector<vector<int>> &image, int threshold)
    {
        int m = image.size();
        int n = image[0].size();
        vector<vector<vector<int>>> regionAverages(m, vector<vector<int>>(n, vector<int>()));
        for (int i = 0; i < m - 2; ++i)
        {
            for (int j = 0; j < n - 2; ++j)
            {
                int regionSum = 0;
                bool valid = true;
                for (int k = 0; k < 3; ++k)
                {
                    for (int l = 0; l < 3; ++l)
                    {
                        if (k < 2 && abs(image[i + k][j + l] - image[i + k + 1][j + l]) > threshold)
                        {
                            valid = false;
                            break;
                        }
                        if (l < 2 && abs(image[i + k][j + l] - image[i + k][j + l + 1]) > threshold)
                        {
                            valid = false;
                            break;
                        }

                        regionSum += image[i + k][j + l];
                    }
                    if (!valid)
                    {
                        break;
                    }
                }
                if (valid)
                {
                    for (int k = 0; k < 3; ++k)
                    {
                        for (int l = 0; l < 3; ++l)
                        {
                            regionAverages[i + k][j + l].push_back(regionSum / 9);
                        }
                    }
                }
            }
        }

        vector<vector<int>> result(m, vector<int>(n, 0));
        for (int i = 0; i < m; ++i)
        {
            for (int j = 0; j < n; ++j)
            {
                if (!regionAverages[i][j].empty())
                {
                    int sum = 0;
                    for (int k = 0; k < regionAverages[i][j].size(); ++k)
                    {
                        sum += regionAverages[i][j][k];
                    }
                    result[i][j] = sum / regionAverages[i][j].size();
                }
                else
                {
                    result[i][j] = image[i][j];
                }
            }
        }
        return result;
    }
};